package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.entity.ExecuteResult;
import org.elec.mac.entity.SBasics;
import org.elec.mac.entity.SBasicsFormula;
import org.elec.mac.entity.SMaterial;
import org.elec.mac.page.PageList;
import org.elec.mac.page.PageProperty;
import org.elec.mac.service.SBasicsFormulaService;
import org.elec.mac.service.SBasicsService;
import org.elec.mac.service.SMaterialService;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class BasicsController extends BaseController {

    @Autowired
    private SBasicsService sBasicsService;

    @Autowired
    private SBasicsFormulaService sBasicsFormulaService;

    @Autowired
    private SMaterialService sMaterialService;

    @RequestMapping(value = "/basics_list.do")
    public String basicsListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                      @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                      @RequestParam(value = "limit", required = false) String limit,
                                      @RequestParam(value = "page", required = false) String page) throws IOException {
        if("page".equals(action)) {
            PageProperty pp = new PageProperty();
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                this.setPageInfo(request.getCookies(), pp, limit, page);
                PageList<SBasics> lintPageList = sBasicsService.getPageList(pp);
                map.put("success", true);
                map.put("records", lintPageList.getRecords());
                map.put("recordsTotal", lintPageList.getTotalRecords());
                map.put("recordsFiltered", lintPageList.getTotalRecords());
            }
            catch(Exception ex) {
                log.error("基础配方列表获取错误", ex);
                map.put("success", false);
                map.put("msg", "基础列表获取错误");
            }
            response.getWriter().write(JSONUtil.map2json(map));
            return null;
        }
        return "/basics/basics_list";
    }

    @RequestMapping(value = "basicsmate_list.do")
    public String basicsFormulaListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                      @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                      @RequestParam(value = "limit", required = false) String limit,
                                      @RequestParam(value = "basicid", required = false) String basicid) throws IOException {

        Map<String, Object> param = new HashMap<>();
        param.put("bid", Utils.parseLong(basicid, 0L));
        List<Map<String, Object>> basicMateList = sBasicsFormulaService.getBasicList(param);

        model.put("basicMateList", basicMateList);
        param.clear();
        param.put("id", Utils.parseLong(basicid, 0L));
        SMaterial sMaterial = sMaterialService.get(param);
        model.put("sBasics", sMaterial);
        return "/basics/basics_mate_list";
    }

    @RequestMapping(value = "/basics_add.do")
    public void basicsAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                   @RequestParam(value = "action", required = false, defaultValue = "") String action) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("do".equals(action)) {
            try {
                String name = this.getParameter(request, "name");
                String unit = this.getParameter(request, "unit");
                Map<String, Object> param = new HashMap<>();
                param.put("name", name);
                SBasics sBasics = sBasicsService.get(param);
                if(null != sBasics) {
                    result.setSuccess(false);
                    result.setMsg("配方名已存在");
                }
                if(StringUtils.isBlank(name)) {
                    result.setSuccess(false);
                    result.setMsg("配方名不能为空");
                }
                if(result.isSuccess()) {
                    SBasics sBasics1 = new SBasics();
                    sBasics1.setName(name);
                    sBasics1.setUnit(unit);
                    sBasics1.setTotal((long)0);
                    sBasics1.setFlag(true);
                    sBasicsService.insert(sBasics1);
                    log.info("基础配方新增");
                }
            } catch(Exception ex) {
                log.error("基础配方新增错误", ex);
                result.setSuccess(false);
                result.setMsg("基础配方新增错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping(value = "/basics_edit.do")
    public void basicsEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                    @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                    @RequestParam(value = "id", required = false, defaultValue = "") String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SBasics sBasics = sBasicsService.get(params);
                result.getBody().put("sBasics", sBasics);
                log.info("配方修改开启");
            } catch(Exception ex) {
                log.error("配方修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("配方修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            try {
                String name = this.getParameter(request, "name");
                String unit = this.getParameter(request, "unit");
                if(StringUtils.isBlank(name)) {
                    result.setSuccess(false);
                    result.setMsg("配方名不能为空");
                }
                if(result.isSuccess()) {
                    SBasics sBasics = new SBasics();
                    sBasics.setId(Utils.parseLong(id, 0L));
                    sBasics.setName(name);
                    sBasics.setUnit(unit);
                    sBasicsService.update(sBasics);
                    log.info("配方修改");
                }
            } catch(Exception ex) {
                log.error("配方修改错误", ex);
                result.setSuccess(false);
                result.setMsg("配方修改错误");
            }
        }
        if("doDelete".equals(action)) {
            try {
                SBasics sBasics = new SBasics();
                sBasics.setId(Utils.parseLong(id, 0L));
                sBasics.setFlag(false);
                sBasicsService.update(sBasics);
                log.info("配方删除");
            } catch(Exception ex) {
                log.error("配方删除错误", ex);
                result.setSuccess(false);
                result.setMsg("配方删除错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping(value = "/basicmate_add.do")
    public void basicMateAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                     @RequestParam(value = "basicid", required = false, defaultValue = "") String basicid)
            throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        Map<String, Object> param = new HashMap<>();
        String bid = request.getParameter("basicid");
        String mid = request.getParameter("materiaid");
        String count = request.getParameter("matercount");
        if("do".equals(action)) {
            try {
                SBasicsFormula sBasicsFormula = new SBasicsFormula();
                sBasicsFormula.setBid(Utils.parseLong(bid,0));
                sBasicsFormula.setMid(Utils.parseLong(mid,0));
                sBasicsFormula.setCount(Utils.parseLong(count,0));
                sBasicsFormulaService.insert(sBasicsFormula);
                //更新基础配方的总克数
//                param.put("id", bid);
//                SBasics basics = sBasicsService.get(param);
//                basics.setTotal(basics.getTotal()+Utils.parseLong(count,0));
//                sBasicsService.update(basics);
            } catch(Exception ex) {
                log.error("配方原料新增错误", ex);
                result.setSuccess(false);
                result.setMsg("配方原料新增错误");
            }
        } else {
            List<Map<String, Object>> materials = sBasicsFormulaService.getBasicMate(Utils.parseLong(bid,0));
            result.getBody().put("materList", materials);
        }

        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    //机台原料修改
    @RequestMapping(value = "/basicmate_edit.do")
    public void basicmateEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                           @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                           @RequestParam(value = "id", required = false, defaultValue = "") String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SBasicsFormula sBasicsFormula = sBasicsFormulaService.get(params);
                result.getBody().put("sBasicsFormula", sBasicsFormula);
                log.info("原料明细修改开启");
            } catch(Exception ex) {
                log.error("原料明细修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("原料明细修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            try {
                Long basicmateid = Utils.parseLong(this.getParameter(request, "basicmateid"), 0L);
                Long amount = Utils.parseLong(this.getParameter(request, "count"),0);
                if(result.isSuccess() && amount == 0) {
                    result.setSuccess(false);
                    result.setMsg("原料克数不能为空");
                }
                if(result.isSuccess()) {
                    SBasicsFormula sBasicsFormula = new SBasicsFormula();
                    sBasicsFormula.setId(basicmateid);
                    sBasicsFormula.setCount(amount);
                    sBasicsFormulaService.update(sBasicsFormula);
                    log.info("原料明细修改");
                    //更新并重新计算机台菜单中的产品库存


                }
            } catch(Exception ex) {
                log.error("原料明细修改错误", ex);
                result.setSuccess(false);
                result.setMsg("原料明细修改错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping(value = "/basicmate_delete.do")
    public void basicMateDeleteHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                       @RequestParam(value = "basicmaid", required = false,defaultValue = "") String basicmaid )
            throws Exception {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("id", Utils.parseLong(basicmaid, 0L));
            sBasicsFormulaService.delete(param);
            log.info("配方原料删除");
        } catch(Exception ex) {
            log.error("配方原料删除错误", ex);
            result.setSuccess(false);
            result.setMsg("配方原料删除错误");
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
}
